package pers.yurwisher.rubick.common.security;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import pers.yurwisher.rubick.common.constant.CacheConstant;
import pers.yurwisher.rubick.common.service.CustomRedisCacheService;
import pers.yurwisher.rubick.common.user.CustomTokenCache;
import pers.yurwisher.rubick.common.user.CustomUserDetails;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求凭证过滤器
 *
 * @author yq 2021年4月22日 21:01:02
 */
@Slf4j
public class TokenFilter extends GenericFilterBean {

    private final TokenProvider tokenProvider;
    private final CustomRedisCacheService customRedisCacheService;

    public TokenFilter(TokenProvider tokenProvider, CustomRedisCacheService customRedisCacheService) {
        this.tokenProvider = tokenProvider;
        this.customRedisCacheService = customRedisCacheService;
        log.info("init tokenFilter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = tokenProvider.getToken(httpServletRequest);
        if (StrUtil.isNotBlank(token)) {
            //依据Token 获取鉴权信息
            CustomTokenCache customTokenCache = customRedisCacheService.get(CacheConstant.Strings.AUTH, token);
            if (customTokenCache != null) {
                //当前会话存入用户信息 用于权限校验
                CustomUserDetails principal = new CustomUserDetails(customTokenCache.getUser());
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(principal, token, principal.getAuthorities()));
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
